import fetch from "node-fetch";
import common from "../../lib/common/common.js";
﻿import plugin from '../../lib/plugins/plugin.js'
import moment from 'moment'
import fs from 'fs'
import yaml from "yaml"
import sharp from 'sharp'
import pLimit from 'p-limit'

let maxnum = 30  //并发限制

let cooldowns = new Map();
let NumReg = '[一壹二两三四五六七八九十百千万亿\\d]+'
export class pixiv extends plugin {
    constructor() {
        super({
            /** 功能名称 */
            name: "vilipix",
            /** 功能描述 */
            dsc: "pixiv",
            /** https://oicqjs.github.io/oicq/#events */
            event: "message",
            /** 优先级，数字越小等级越高 */
            priority: 5000,
            rule: [                
				{
                    reg: "^#pix搜图(.*)$",
                    fnc: 'tags'
                },	
            ]
        });
    }
	
	
  async tags(e) {	
	if (!e.isGroup) {
	    return;
    }
    let groupId = e.group_id
    let cfg = await loadcfg(groupId)
	if (!cfg && !e.isMaster) return
	
    if (!cfg.setu && !e.isMaster) {
	     logger.mark(`${groupId} 涩图权限 ${cfg.setu}`)
         return;
    }
     let tag = e.msg.replace(/#|pix搜图/g, '').trim()
	     tag = tag.replace('原图', '');
	 let pageMatch = e.msg.match(new RegExp(`第(${NumReg})页`));
	  let page = 1;
      if (pageMatch) {
          page = Number(pageMatch[1]);
      if (isNaN(page)) {
          e.reply('请输入阿拉伯数字');
          return;
          }
        tag = tag.replace(pageMatch[0], "").trim();  // 去掉匹配的页码部分
      }
	  
        let num = (page - 1) * 20;
        let url = `https://www.vilipix.com/api/v1/picture/public?&tags=${tag}&limit=20&sort=new&offset=${num}`;
		let response = ""
		let res = ""
            try {
                response = await fetch(url);
                res = await response.json();
			} catch (error) {
                e.reply('请求失败',true,{ recallMsg: 5 })
                return
            }
		    if (res.data.rows.length == 0) {
                e.reply(`没有相关内容`,true,{ recallMsg: 5 });
                return
            }  
        if (!e.isMaster ) {
	        const cooldown = cooldowns[groupId];
	        if (cooldown && cooldown > Date.now()) {
                const remainingTime = Math.ceil((cooldown - Date.now()) / 1000);
                e.reply(`lsp注意身体，请${remainingTime}秒后再来～`,false,{ recallMsg: 10 });
                return;
            }
            cooldowns[groupId] = Date.now() + cfg.cd * 1000;
	    }			
    let msgs = [];
    e.reply(`vilipix 开始执行任务${tag}[${page}]，数量${res.data.rows.length}...`,false,{ recallMsg: 5 })
    msgs.push(`${e.msg}`)
    
	// 设置并发限制
    const limit = pLimit(maxnum)
	let imgsize = e.msg.includes('原图') ? 'original_url' : 'regular_url'
	    // 使用 Promise.all 和 p-limit 并行下载图片
        await Promise.all(res.data.rows.map((k, index) => limit(async () => {
            try {
                let image = await fetch(k[imgsize]); //regular_url original_url
                let imageData = Buffer.from(await image.arrayBuffer());
                let flippedImage = await sharp(imageData).flop().toBuffer();
		        msgs.push([
                    `【标题】${k.title}\n`,
		            `【id】${k.picture_id}\n`,
		            `【日期】${moment(k.created_at).format('YYYY-MM-DD HH:mm:ss')}\n`,
		            `【tags】${k.tags}\n`,
					segment.image(flippedImage)
                  ])
                logger.info(`vilipix 图片${index+1}处理 ok`);
            } catch (error) {
				msgs.push([
                    `【标题】${k.title}\n`,
		            `【id】${k.picture_id}\n`,
		            `【日期】${moment(k.created_at).format('YYYY-MM-DD HH:mm:ss')}\n`,
		            `【tags】${k.tags}\n`,
			        segment.image(k[imgsize])
                  ])
                logger.error(`vilipix 图片${index+1}处理 failed`);
            }
        })));
	  
	let ForwardMsg = await common.makeForwardMsg(e,msgs);
    await e.reply(ForwardMsg,false,{ recallMsg: cfg.recall })

    return true	
  }

}

async function loadcfg(id) {
	let file = `data/pixiv.yaml`
    if (!fs.existsSync(file)) return false
	
    let data = yaml.parse(fs.readFileSync(file, 'utf8'))
	if (!data[id]) return false
	
	return data[id]
}